package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	gpt3 "github.com/PullRequestInc/go-gpt3"
	wechat "github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	offConfig "github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/silenceper/wechat/v2/officialaccount/message"
)

func init() {
	log.New(os.Stdout, "TRACE: ", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
}

func serveWechat(rw http.ResponseWriter, req *http.Request) {
	wc := wechat.NewWechat()
	//这里本地内存保存access_token，也可选择redis，memcache或者自定cache
	memory := cache.NewMemory()
	cfg := &offConfig.Config{
		AppID:          "wx83236bb897712804",
		AppSecret:      "2da6d2476cdb29da81c2f16304d07b6d",
		Token:          "weixin",
		EncodingAESKey: "Q2V63f7oC3vgNFAKV5RK1695zFrVHdNNw9EIHiBqjyp",
		Cache:          memory,
	}
	officialAccount := wc.GetOfficialAccount(cfg)

	// 传入request和responseWriter
	server := officialAccount.GetServer(req, rw)

	//设置接收消息的处理方法
	server.SetMessageHandler(func(msg *message.MixMessage) *message.Reply {
		// 调用chatgpt
		apiKey := "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"

		ctx := context.Background()
		client := gpt3.NewClient(apiKey)

		question := msg.Content
		resp, err := GetResponse(client, ctx, question)
		if err != nil {
			log.Fatalln("err", err)
		}
		fmt.Println(resp)
		if err != nil {
			log.Fatalln(err)
		}
		log.Println(resp)
		//回复消息：演示回复用户发送的消息
		text := message.NewText(strings.TrimPrefix(resp, "\n\n"))
		return &message.Reply{MsgType: message.MsgTypeText, MsgData: text}
	})

	//处理消息接收以及回复
	err := server.Serve()
	if err != nil {
		log.Println(err)
		return
	}
	//发送回复的消息
	server.Send()
}

func GetResponse(client gpt3.Client, ctx context.Context, quesiton string) (string, error) {
	resp, err := client.CompletionWithEngine(ctx, gpt3.TextDavinci003Engine, gpt3.CompletionRequest{
		Prompt: []string{
			quesiton,
		},
		MaxTokens:   gpt3.IntPtr(3000),
		Temperature: gpt3.Float32Ptr(0),
	})
	if err != nil {
		return "", err
	}
	return resp.Choices[0].Text, nil
}

func main() {
	http.HandleFunc("/", serveWechat)
	log.Println("wechat server listener at", ":8001")
	err := http.ListenAndServe(":8001", nil)
	if err != nil {
		log.Printf("start server error , err=%v", err)
	}
}
